package com.syt.sms.config;

import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.annotation.Bean;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

/**
 * @Author: xxx
 * @Date: 2023/2/4 23:38
 * @Description: 全局处理日期格式化类
 */
@JsonComponent
public class LocalDateTimeSerializeConfig {

    @Value("${spring.jackson.format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;
    

    /**
     * Date类型全局时间格式化
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {
        return builder -> {
            TimeZone timeZone = TimeZone.getTimeZone("GMT+8");//获取时区
            SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);//设置格式化模板
            dateFormat.setTimeZone(timeZone);
            builder.failOnEmptyBeans(false)
                    .failOnUnknownProperties(false)
                    .featuresToDisable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS)
                    .dateFormat(dateFormat);
        };
    }

    /**
     * LocalDateTime类型全局时间格式化
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeSerializer(){
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }
    
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(){
        return builder->builder.serializerByType(LocalDateTime.class,localDateTimeSerializer());
    }




}
